package com.ruoyi.common.utils;

/**
 * ascii BBC异或校验
 */
public class YiHuoUtils {
    public static void main(String[] args) {

        System.out.println(yiHuo("HXALA,1#----------,2#R---1-----"));

    }

    /**
     * ascii 转16进制
     *
     * @param asciiChar ascii字符串
     * @return 16进制字符串
     */
    public static String asciiToHex(String asciiChar) {
        byte[] bytes = String.valueOf(asciiChar).getBytes();
        StringBuilder hex = new StringBuilder();
        for (byte b : bytes) {
            hex.append(String.format("%02X", b));
        }
        return hex.toString();
    }

    /**
     * 数据校验 异或处理
     */
    public static String yiHuo(String content) {
        if (StringUtils.isEmpty(content)) {
            return null;
        }
        content = asciiToHex(content);
        int a = 0;
        for (int i = 0; i < content.length() / 2; i++) {
            a = a ^ Integer.parseInt(content.substring(i * 2, (i * 2) + 2), 16);
        }
        String result = Integer.toHexString(a);
        if (result.length() == 1) {
            return "0" + result;
        } else {
            return result;
        }
    }

}
